<template>
  <div class="container">
    <el-form :model="form" label-width="auto" style="max-width: 600px" :inline="true">
      <el-form-item>
        <el-button type="primary" @click="toAdd">添加</el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="code" label="常数类别编码" width="180"/>
        <el-table-column prop="name" label="常数类别名称" width="180"/>
        <el-table-column label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="row.isDeleted ? 'danger' : 'success'">
              {{ row.isDeleted ? '已禁用' : '已启用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="toEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.isDeleted ? 'success' : 'danger'"
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.isDeleted ? '启用' : '禁用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.isDeleted === 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog 
      v-model="editDialogFormVisible" 
      :title="editForm.id ? '编辑常数类别' : '添加常数类别'" 
      width="500"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="常数类别编码" prop="code">
          <el-input v-model="editForm.code"/>
        </el-form-item>
        <el-form-item label="常数类别名称" prop="name">
          <el-input v-model="editForm.name"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="editDialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'

const form = ref({})
const editForm = ref({
  id: null,
  code: '',
  name: '',
  isDeleted: 0
})
const editDialogFormVisible = ref(false)
const tableData = ref([])
const loading = ref(false)

// 获取列表数据
async function listData() {
  try {
    loading.value = true
    const data = await service.get("/constantType/list")
    tableData.value = Array.isArray(data) ? data : []
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('Error:', error)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 保存数据
async function save() {
  try {
    if (!editForm.value.code || !editForm.value.name) {
      ElMessage.error('请填写完整信息')
      return
    }

    const apiUrl = editForm.value.id 
      ? `/constantType/update` 
      : `/constantType/add`
      
    await service.post(apiUrl, editForm.value)
    
    ElNotification.success(editForm.value.id ? '更新成功' : '添加成功')
    editDialogFormVisible.value = false
    listData()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 切换状态
function toggleStatus(row) {
  ElMessageBox.confirm(
    `确认要${row.isDeleted ? '启用' : '禁用'}该类别吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await service.post(`/constantType/status`, {
        id: row.id,
        isDeleted: row.isDeleted ? 0 : 1
      })
      ElMessage.success('状态更新成功')
      listData()
    } catch (error) {
      ElMessage.error('状态更新失败')
    }
  })
}

// 删除数据
function handleDelete(row) {
  ElMessageBox.confirm(
    '确认要永久删除该类别吗？此操作不可恢复！',
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(async () => {
    try {
      await service.delete(`/constantType/delete/${row.id}`)
      ElMessage.success('删除成功')
      listData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

function toAdd() {
  editForm.value = {
    id: null,
    code: '',
    name: '',
    isDeleted: 0
  }
  editDialogFormVisible.value = true
}

function toEdit(row) {
  editForm.value = { ...row }
  editDialogFormVisible.value = true
}

onMounted(() => {
  listData()
})
</script>

<style scoped>
.container {
  padding: 20px;
}
</style>